<?php 
class ioLoginQQ
{ 

    public function __construct(){ 

    }

    function login($appid, $scope, $callback) {
        $_SESSION['rurl'] = $_REQUEST ["loginurl"];
        $_SESSION ['state'] = md5 ( uniqid ( rand (), true ) ); //CSRF protection
        $params=array(
            'response_type'=>'code',
            'client_id'=>$appid,
            'state'=>$_SESSION ['state'],
            'scope'=>$scope,
            'redirect_uri'=>$callback
        );
        $login_url = 'https://graph.qq.com/oauth2.0/authorize?'.http_build_query($params);
        wp_redirect($login_url, 302);
        exit;
    }
    function callback($appid,$appkey,$path) {
        if ($_REQUEST ['state'] == $_SESSION ['state']) {
            $params=array(
                'grant_type'=>'authorization_code',
                'code'=>$_REQUEST ["code"],
                'client_id'=>$appid,
                'client_secret'=>$appkey,
                'redirect_uri'=>$path
            );
            $token_url = 'https://graph.qq.com/oauth2.0/token?'.http_build_query($params);
            
            $response = wp_remote_get( $token_url );
            $body = wp_remote_retrieve_body($response);
            if(preg_match('/callback\((.*)\)/', $body, $matches)){
                $msg = json_decode(trim($matches[1]));
                if(isset($msg->error)){
                    wp_die($msg->error.': '.$msg->error_description, __('获取 QQ Access Token 失败', 'i_theme'), array('response'=>403));
                }
            }
            
            $params = array ();
            parse_str ( $body, $params );
            $_SESSION ['qq_access_token'] = $params ["access_token"];
            $_SESSION ['qq_refresh_token'] = $params ["refresh_token"];
            $_SESSION ['qq_token_expiration'] = $params ["expires_in"];
        } else {
            echo ("The state does not match. You may be a victim of CSRF.");
            exit;
        }
    }
    function get_openid() {
        $graph_url = "https://graph.qq.com/oauth2.0/me?access_token=" . $_SESSION ['qq_access_token'];
        
        $response = wp_remote_get( $graph_url );
        $body = wp_remote_retrieve_body($response);
        $msg = null;
        if(preg_match('/callback\((.*)\)/', $body, $matches)){
            $msg = json_decode(trim($matches[1]));
            if(isset($msg->error)){
                wp_die($msg->error.': '.$msg->error_description, __('获取 QQ OpenID 失败', 'i_theme'), array('response'=>403));
            }
        }
        if(!$msg){
            parse_str($body, $params);
            $msg = (object)$params;
        }
        $_SESSION ['qq_openid'] = $msg->openid;
    }
    function get_user_info() {
        $params=array(
            'access_token'=>$_SESSION ['qq_access_token'],
            'oauth_consumer_key'=>io_get_option('open_qq_key')['appid'],
            'openid'=>$_SESSION ['qq_openid'],
            'format'=>'json'
        );
        $get_user_info = 'https://graph.qq.com/user/get_user_info?' . http_build_query($params);        
        $info = json_decode(wp_remote_retrieve_body(wp_remote_get($get_user_info)));//$this->urlUtils->get_contents( $get_user_info );
        if ($info->ret){
            wp_die($info->ret.': '.$info->msg, __('获取 QQ 用户信息失败', 'i_theme'), array('response'=>403));
        }
        return $info;
    }
    function use_db(){
        if(isset($_SESSION['qq_openid'])){
            global $wpdb;
            
            if(is_user_logged_in()){
                $userid = wp_get_current_user()->ID;
                $user_ID = $wpdb->get_var("SELECT ID FROM $wpdb->users WHERE qq_id='".esc_sql($_SESSION['qq_openid'])."'");
                if($user_ID && $user_ID != $userid)
                { 
                    wp_die("该账号已经存在，不能绑定到当前账号！", __('绑定失败', 'i_theme'), array('response'=>403));
                }
                $wpdb->query("UPDATE $wpdb->users SET qq_id = '".esc_sql($_SESSION['qq_openid'])."' WHERE ID = '$userid'");
                $uinfo = $this->get_user_info();
                update_user_meta($userid, 'qq_avatar', $uinfo->figureurl_qq_2);
                update_user_meta($userid, 'qq_name', $uinfo->nickname);
                update_user_meta($userid, 'qq_openid', esc_sql($_SESSION['qq_openid']));
            }

            $user_ID = $wpdb->get_var("SELECT ID FROM $wpdb->users WHERE qq_id='".esc_sql($_SESSION['qq_openid'])."'");
            if ($user_ID) {
                wp_set_auth_cookie($user_ID,true,is_ssl());
                wp_redirect($_SESSION['rurl']);
                if(get_user_meta($user_ID, 'qq_avatar' )){
                    $uinfo = $this->get_user_info();
                    update_user_meta($user_ID, 'qq_avatar', $uinfo->figureurl_qq_2);
                    update_user_meta($user_ID, 'qq_name', $uinfo->nickname);
                    update_user_meta($user_ID, 'qq_openid', esc_sql($_SESSION['qq_openid']));
                }
                exit();
            }else{
                $prename = 'io';
                $extname = rand(1000000,9999998);
                $login_name = $prename.$extname;
                if(username_exists($login_name)){
                    while(username_exists($login_name)){ $extname++; }
                    $login_name = $prename.$extname;
                }
                $pass = wp_generate_password();
                $uinfo = $this->get_user_info();
                $username = $uinfo->nickname;
                $userdata=array(
                    'user_login' => $login_name,
                    'user_email' => $login_name.'@io.com',
                    'display_name' => $username,
                    'user_pass' => $pass,
                    'nickname' => $username,
                    'role' => get_option('default_role')
                );
                $user_id = wp_insert_user( $userdata );
                if ( is_wp_error( $user_id ) ) {
                    echo $user_id->get_error_message();
                }else{
                    $ff = $wpdb->query("UPDATE $wpdb->users SET qq_id = '".esc_sql($_SESSION['qq_openid'])."' WHERE ID = '$user_id'");
                    if ($ff) {
                        update_user_meta($user_id, 'avatar', $uinfo->figureurl_qq_2);
                        update_user_meta($user_id, 'qq_avatar', $uinfo->figureurl_qq_2);
                        update_user_meta($user_id, 'qq_name', $uinfo->nickname);
                        update_user_meta($user_id, 'name_change', 1);
                        update_user_meta($user_id, 'qq_openid', esc_sql($_SESSION['qq_openid']));
                        update_user_meta($user_id, 'avatar_type', 'qq');
                        wp_set_auth_cookie($user_id,true,is_ssl());
                        wp_redirect($_SESSION['rurl']);
                    }          
                }
                exit();
            }
        }
    } 
}

?>